/**************************************************************************************
*  Rtc.java
*  Program demonstrating the use of PWM with LPC21xx to control servo motor.
**************************************************************************************
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
* OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY,  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL RTJ COMPUTING BE LIABLE FOR ANY CLAIM, DAMAGES
* OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*
* Created by:
*      RTJ Computing
**************************************************************************************/
import lpc2xxx.edu.*;
import lpc2xxx.hw.*;


class Servo
{
    // duty is controlled in 0.01% increments
    final static int center = 700; 
    static Switch sw = new Switch();
    static int freq = 50;
    
    static void main(String[] args) 
    {
        Console.println("");
        Console.println("LPC21xx servo control with PWM2");
        Console.println("This program is for use with LPC2148 Education board");
        Console.println("Press joystick left/right switch to change servo position");
        Console.println("To exit press ESC");
        Console.println("");

        Console.println("Connect a servo to J55 (ensuring correct wire polarity), then press ENTER");
        while (Console.getKey() != Console.CR)
            ;

        sw.start();

        PWM.init(PWM.PWM2, freq);
        int duty = center;
        int newDuty = duty;
        setDuty(duty);
        while (true)
        {
            if (Console.getKey() == Console.ESC)
                break;

            newDuty = duty;
            if (sw.left() && duty > 100)
                newDuty -= 20;
            else if (sw.right() && duty < 2000)
                newDuty += 20;
            else if (sw.center() && duty != center)
                newDuty = center;

            if (newDuty != duty)
            {
                duty = newDuty;
                setDuty(duty);
                sleep(150);
            }

        }
        setDuty(center);
        sleep(300);
        setDuty(0);
    }

    static void setDuty(int duty)
    {
        PWM.duty(PWM.PWM2, duty);
        PWM.apply();

        Console.print("\rDuty: " + (duty / 100) + "." + ((duty / 10) % 10) + "% ");
    }

    static void sleep(int ms)
    {
        try 
        {
            Thread.sleep(ms);
        }
        catch (InterruptedException e) {}
    }
}

